import { ElMessage, type FormInstance } from "element-plus";
import { request } from "../../../utils/request";
import { publishTask } from "../../../api/modules/course";
import { getCourseList } from "./useProject";

interface Task {
  des: string;
  courseId: string;
  description: string;
  file?: File;
}
export function useTask() {
  const homeworkRef = ref<any>();
  const assignmentFormRef = ref<FormInstance>();
  const assignmentDialogVisible = ref(false);
  const assignmentForm = reactive<Task>({
    des: "",
    courseId: "",
    description: "",
  });

  watch(
    () => assignmentDialogVisible.value,
    (val) => {
      if (val) {
        assignmentForm.des = "";
        assignmentForm.courseId = "";
        assignmentForm.file = undefined;
        assignmentFormRef.value?.clearValidate();
      }
    }
  );

  function saveAssignment() {
    const formData = new FormData();
    formData.append("courseId", assignmentForm.courseId);
    if (assignmentForm.file) {
      formData.append("file", assignmentForm.file);
    }
    formData.append("des", assignmentForm.des);
    request({
      fn: publishTask,
      params: [formData],
      success: () => {
        ElMessage.success("发布成功");
        assignmentFormRef.value?.resetFields();
        assignmentDialogVisible.value = false;
        homeworkRef.value?.getHomework();
        getCourseList();
      },
    });
  }

  function uploadTaskFile() {
    const input = document.createElement("input");
    input.type = "file";
    input.onchange = (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (file) {
        assignmentForm.file = file;
      }
    };
    input.click();
  }

  return {
    assignmentFormRef,
    assignmentDialogVisible,
    assignmentForm,
    saveAssignment,
    uploadTaskFile,
    homeworkRef,
  };
}
